package com.ms.jsf.omnifaces;

import javax.faces.model.SelectItem;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Helper class to build an array of SelectItems using various means, like via the builder pattern or a given <code>Map</code>.
 *
 * @author Arjan Tijms
 */
public class SelectItemsBuilder {

    List<SelectItem> selectItems = new ArrayList<SelectItem>();

    public SelectItemsBuilder add(Object value, String label) {
        selectItems.add(new SelectItem(value, label));
        return this;
    }

    public SelectItem[] build() {
        return selectItems.toArray(new SelectItem[selectItems.size()]);
    }

    public List<SelectItem> buildList() {
        return selectItems;
    }

    /**
     * Builds a <code>List</code> of <code>SelectItem</code>s from the given <code>Map</code> argument.
     *
     * @param map the Map
     * @return <code>List</code> of <code>SelectItem</code>s having the map's value as value and the map's key as label.
     */
    public static List<SelectItem> fromMap(Map<?, ?> map) {
        List<SelectItem> items = new ArrayList<SelectItem>(map.size());
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            items.add(new SelectItem(entry.getValue(), entry.getKey().toString()));
        }

        return items;
    }

}
